package com.blue.rpc.client;

import com.blue.rpc.core.codec.MessageProtostuffDecoder;
import com.blue.rpc.core.codec.MessageProtostuffEncoder;
import com.blue.rpc.core.message.RpcResponse;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

public class RpcClientInitializer extends ChannelInitializer<SocketChannel>
{
	private final NettyRpcClient rpcClient;
	private final String token;

	public RpcClientInitializer(NettyRpcClient rpcClient, String token)
	{
		this.rpcClient = rpcClient;
		this.token = token;
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception
	{
		ChannelPipeline cp = ch.pipeline();

		// 空闲心跳
		cp.addLast(new IdleStateHandler(50, 30, 20));

		// 获取完整数据包
		cp.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 0));

		// 编码/解码器
		// cp.addLast(new MessageJsonEncoder());
		// cp.addLast(new MessageJsonDecoder(RpcResponse.class));
		cp.addLast(new MessageProtostuffEncoder());
		cp.addLast(new MessageProtostuffDecoder(RpcResponse.class));

		// 心跳处理器
		cp.addLast(new HeartbeatHandler());

		// 业务处理器
		cp.addLast(new TcpClientHandler(rpcClient, token));
	}

}
